﻿#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void CountSort(int* a, int n) {
	//1.找出最大值最小值确定range
	int max = a[0];
	int min = a[0];
	for (int i = 0; i < 10; i++) {
		if (a[i] < min) {
			min = a[i];
		}
		if (a[i] > max) {
			max = a[i];
		}
	}
	int range = max - min + 1;
	//2.建立一个range大小的新数组用来映射
	int* count = (int*)calloc(range,sizeof(int));//void* calloc (size_t num, size_t size);
	//int* count = (int*)malloc(sizeof(int) * range);
	if (count == NULL) {
		perror("calloc fail");
		return;
	}
	//memset(count, 0, sizeof(int) * range);
	for (int i = 0; i < 10; i++) {
		count[a[i] - min]++;
	}

	int k = 0;
	for (int j = 0; j < range; j++) {
		while (count[j]--) {
			a[k++] = min + j;
		}
	}
	free(count);//忘记释放不再使⽤的动态开辟的空间会造成内存泄漏
}
int main() {
	int a[10] = { 114,114,113,117,117,115,115,128,128,110 };
	CountSort(a, 10);
	for (int i = 0; i < 10;i++) {
		printf("%d ",a[i]);
	}
	return 0;
}
